import { Button, Form, Input, message } from 'antd';
import { UserOutlined, UnlockFilled} from '@ant-design/icons';
import { getIdByName, login, getPermissionInfo } from '../../api/index' 
import { useNavigate } from 'react-router-dom'
import './index.scss'

function Login() {
  const navigate = useNavigate()

  const onFinish = async (e:any) => {
    const byres = await getIdByName({
      username: '代理商后台项目',
      password: e.password
    })
    const res:any = await login({...e}, byres.data)
    console.log(res)
    if (res.code === 0) {
      sessionStorage.setItem('token', res.data.accessToken)
      getUserInfo()
    } else {
      message.error(res.msg)
    }
  }

  const onFinishFailed = (e:any) => {
    console.log(e)
  }

  const getUserInfo = async () => {
    const res:any = await getPermissionInfo()
    console.log(res)
    if (res.code === 0) {
      navigate('/')
    } else {
      message.error(res.msg)
    }
  }

  return <div className="login">
    <div className='login-form'>
      <div className="login-form-title">有猿医学代理商后台管理</div>
      <Form
        name="wrap"
        wrapperCol={{ flex: 1 }}
        colon={false}
        style={{ maxWidth: 600 }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item name="username" rules={[{ required: true, message: '请输入账号' }]}>
          <Input prefix={<UserOutlined />} placeholder='请输入账号'/>
        </Form.Item>

        <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
          <Input type='password' prefix={<UnlockFilled />} placeholder='请输入密码'/>
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" block>
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  </div>
}

export default Login